package org.example.seckill.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.example.seckill.bean.User;
import org.example.seckill.mapper.UserMapper;
import org.example.seckill.service.UserService;
import org.example.seckill.util.CookieUtils;

import org.example.seckill.util.UUIDUtil;
import org.example.seckill.util.ValidatorUtil;
import org.example.seckill.vo.LoginVo;
import org.example.seckill.vo.RespBean;
import org.example.seckill.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author woopsion
 * @date 2025-06-28
 */
@Service
@Slf4j
public class UserServiceImpl  extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    
    @Override
    public RespBean login(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {

        Long mobile = loginVo.getMobile();
        String password = loginVo.getPassword();

        /**
         * 传入 “” 空值报错
         */
        if(!StringUtils.hasText(password)){return RespBean.error(RespBeanEnum.Error);}
        /**
         * 手机格式错误
         */
        if(!ValidatorUtil.isMobile(mobile)){return RespBean.error(RespBeanEnum.MOBILE_ERROR);}

        User user = userMapper.selectById(mobile);
        System.out.println("====================="+user+"============================");
        if(user == null){
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }
        /**
         * 高并发是重点，这里的密码加密过程可以先忽略掉
         * 这里仅仅就是一个密码明文存放。数据库也同理
         */
//        //密码错误
//        if(!MD5util.midPassToDBPass(mobile,user.getSalt()).equals(user.getPassword())){return RespBean.error(RespBeanEnum.LOGIN_ERROR);}
        if(!loginVo.getPassword().equals(user.getPassword())){ return RespBean.error(RespBeanEnum.LOGIN_ERROR);}
        //登陆成功
        String ticket = UUIDUtil.getUUID();
        //为了分布式系统，将用户登录信息集中存放在redis服务器上
        redisTemplate.opsForValue().set("user:"+ticket,user);
//        request.getSession().setAttribute(ticket,user);
        //将ticket票据保存在客户端浏览器的cookie上面
        CookieUtils.setCookie(response,"userTicket",ticket);
        return RespBean.success();
    }

    @Override
    public User getUserByCookieTicket(String ticket, HttpServletRequest request,HttpServletResponse response) {
        if(!StringUtils.hasText(ticket)){return null;}
        User user = (User)redisTemplate.opsForValue().get("user:"+ticket);
        
        //此处获取到了用户的相应信息就应该刷新一下cookie的值
        CookieUtils.setCookie(response,"userTicket",ticket);
        return user;
    }
}
